package com.sharemarking.wa.platform.service;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sharemarking.wa.common.ResponseParams;
import com.sharemarking.wa.common.entity.Member;
import com.sharemarking.wa.common.entity.Message;
import com.sharemarking.wa.common.entity.OrgMember;
import com.sharemarking.wa.common.exception.RequestException;
import com.sharemarking.wa.platform.config.JGPushConfig;
import com.sharemarking.wa.platform.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author dxy
 */
@Service
public class JGPushService {
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SecurityService ss;
    @Autowired
    private JGPushConfig jgPushConfig;
    @Autowired
    private MemberMapper mm;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private AgreementMapper agreementMapper;
    @Autowired
    private OrgMemberMapper orgMemberMapper;



    public ResponseParams<?> pushAll() throws Exception {
        String alert = request.getParameter("alert");
//        String title = request.getParameter("title");

        pushAll(jgPushConfig.getJPushClient(), alert);
        return ResponseParams.ok(null);
    }

    public ResponseParams<?> pushByAgreementPassed() throws RequestException {
        Integer memberId = ss.getCurrentUserId();
        String content = request.getParameter("content");
        Integer role = memberMapper.getRoleByMemberId(memberId);
        if (role != null && !role.equals(1)) {
            throw RequestException.create(ResponseParams.isDataError("无权限"));
        }
        if (StringUtils.isEmpty(content) || content.equals("")) {
            throw RequestException.create(ResponseParams.isDataError(content));
        }
        for (Integer i:agreementMapper.getOrgId(companyMapper.getCompany(memberId).getCompanyName()))
            for (OrgMember j:orgMemberMapper.selectList(new QueryWrapper<OrgMember>().eq("org_id",i)))
                pushTag("来自" + companyMapper.getCompany(memberId).getCompanyName() + "的消息" + "\n" + content,j.getMemberId(),content,memberId);
        return ResponseParams.ok(null);
    }


    public void pushTag(String messageStr, Integer memberId) {
        Message message = new Message();
        message.setTitle(messageStr);
        message.setMemberId(memberId);
        message.setCreateDate(new Date());
        message.setIsPushSms(0);
        messageMapper.insert(message);

        String alias = memberMapper.getAlias(memberId);
        try {
            buildPushObject_android_tag_alertWithTitle(jgPushConfig.getJPushClient(), messageStr, alias);
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
    }

    public void pushTag(String messageStr, Integer memberId,String content, Integer fromMemberId) {
        Message message = new Message();
        message.setTitle(messageStr);
        message.setBody(content);
        message.setMemberId(memberId);
        message.setCreateDate(new Date());
        message.setIsPushSms(0);
        message.setFromMemberId(fromMemberId);
        messageMapper.insert(message);

        String alias = memberMapper.getAlias(memberId);
        try {
            buildPushObject_android_tag_alertWithTitle(jgPushConfig.getJPushClient(), messageStr, alias);
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
    }



    public void pushAll(JPushClient jpushClient, String alert) {
        try {
            PushResult result = jpushClient.sendPush(PushPayload.alertAll(alert));
            // 请求结束后，调用 NettyHttpClient 中的 close 方法，否则进程不会退出。
            jpushClient.close();

        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
    }

    public void buildPushObject_android_tag_alertWithTitle(JPushClient jpushClient, String alert, String tag) throws APIConnectionException, APIRequestException {
        if (tag == null){
            return;
        }

        PushResult result = jpushClient.sendPush(PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias(tag))
                .setNotification(Notification.alert(alert))
                .build());
        jpushClient.close();
    }


}
